package wangjg.xuexiban.activity.card;

import java.util.HashMap;
import java.util.Map;

import wangjg.xuexiban.R;
import wangjg.xuexiban.data.CardDAO;
import wangjg.xuexiban.util.Constant;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class CardEditablePagerActivity extends BasicCardActivity {
    static final int REQ_ADD = 1;
    static final int REQ_MOD = 2;
    static final int REQ_DEL = 3;
    
	private ViewPager mPager;
	private MyPagerAdapter pagerAdapter;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.card_list2);
		this.initView(0);
	}
	
	//初始化ViewPager
	protected void initView(int index){
        mPager = (ViewPager) findViewById(R.id.vPager);
        pagerAdapter = new MyPagerAdapter();
        mPager.setAdapter(pagerAdapter);
        mPager.setOnPageChangeListener(new DetailOnPageChangeListener());
        if(pagerAdapter.getCount() <= index){
            return;
        }
        mPager.setCurrentItem(index);
        this.currentIndex = index;
	}
    
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, "添加");
		menu.add(0, 2, 2, "编辑");
		menu.add(0, 3, 3, "删除");
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==1){
			Intent intent = new Intent(this, CardEditActivity.class);
			intent.putExtra("category_path", getIntent().getStringExtra("category_path"));
			startActivityForResult(intent, 1);
		}else if(item.getItemId()==2){
			Intent intent = new Intent(this, CardEditActivity.class);
			intent.putExtra("category_path", getIntent().getStringExtra("category_path"));
			if(this.pagerAdapter.getCount()>0)
				intent.putExtra("id", ""+currentIndex);
			startActivityForResult(intent, 2);
		}else if(item.getItemId()==3){
			android.content.DialogInterface.OnClickListener dl = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int which) {
                	if(which==DialogInterface.BUTTON_POSITIVE){
                		onActivityResult(REQ_DEL, 1 ,null);
                	}
                }  
            };
			new AlertDialog.Builder(
					CardEditablePagerActivity.this)
	                .setTitle("删除")
	                .setMessage("确定要删除吗")
	                .setPositiveButton("确定",dl)
	                .setNegativeButton("取消",dl).show();
		}
		return super.onOptionsItemSelected(item);
	}
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(resultCode==1){
    		this.cardDAO.setReloadFlag();
    		if(requestCode==REQ_ADD){
    			this.currentIndex=this.pagerAdapter.getCount()-1;
    			mPager.setCurrentItem(this.currentIndex);
    		}else if(requestCode==REQ_MOD){
//        		this.pagerAdapter.updateView(this.currentIndex);
    		}else if(requestCode==REQ_DEL){
    			deleteItem();
    		}
    	}
    }
    
    private void deleteItem(){
    	int curIndex = this.currentIndex;
    	cardDAO.delete(curIndex);
    	View view = this.mPager.getChildAt(curIndex);
    	this.mPager.removeView(view);
		if(curIndex>0){
			curIndex--;
		}
		
		mPager.setCurrentItem(curIndex);
		currentIndex = curIndex;
		
    }
    
	private CardDAO cardDAO;
	private CardDAO getCardDAO(){
		if(cardDAO==null){
			cardDAO = new CardDAO();
			
			SharedPreferences setting = this.getSharedPreferences(Constant.SHARED_PREFERENCES_NAME, 0);
			String root = setting.getString(Constant.URL_CARD_DOWN, Constant.DEFAULT_DATA_ROOT);
			String path = getIntent().getStringExtra("category_path");
			
			cardDAO.setCategoryPath(root+path);
		}
		return cardDAO;
	}

	class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
	    public void onPageSelected(int position) {
	        currentIndex = position;
	    }
	}

	/**
	 * ViewPager适配器
	 */
	class MyPagerAdapter extends PagerAdapter {
		Map<Integer, View> map = new HashMap<Integer,View>();
		
		public int getCount() {
			return getCardDAO().getCount();
		}
		
		public Object instantiateItem(View container, int position) {
			Log.i(this.getClass().getName(), "instantiateItem, position=" + position	+ ", container=" + container);
			View view = map.get(position);
			if(view==null){
				view = createPageView(position);
				map.put(position, view);
			}
			((ViewPager) container).addView(view);
			return view;
		}
		
		public void destroyItem(View container, int position, Object object) {
			Log.i(this.getClass().getName(), "destroyItem,position=" + position	+ ",object=" + object);
			((ViewPager)container).removeView((View) object);
			this.map.remove(position);
		}
		
		public boolean isViewFromObject(View view, Object object) {
			return view == (object);
		}
		
		public Parcelable saveState() {
			return null;
		}
		
		public void restoreState(Parcelable state, ClassLoader loader) {
		}
		
		public void startUpdate(View container) {
		}
		
		public void finishUpdate(View container) {
		}
	}

}

